package com.sds.sweng.swat.miplatform.ui.design.parts.area;

import java.util.List;

import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.EditPolicy;

import com.sds.sweng.swat.miplatform.ui.design.layouts.EasyGridLayout;
import com.sds.sweng.swat.miplatform.ui.design.models.area.AreaTemplate;
import com.sds.sweng.swat.miplatform.ui.design.models.area.AreaTemplateTitle;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.GridSubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.HorizontalSubAreaContainer;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.SubArea;
import com.sds.sweng.swat.miplatform.ui.design.parts.MiplatformContainerPart;
import com.sds.sweng.swat.miplatform.ui.design.parts.MiplatformDesignPart;
import com.sds.sweng.swat.miplatform.ui.design.policies.DesignComponentEditPolicy;

public abstract class AreaTemplatePart extends MiplatformContainerPart {

	public boolean isSelectable() {
		return true;
	}

	protected IFigure createFigure() {
		Figure f = new Figure();
		f.setLayoutManager(EasyGridLayout.create(2, false, 0, 0, -1, -1));

		return f;
	}

	protected void createEditPolicies() {
		installEditPolicy(EditPolicy.COMPONENT_ROLE, new DesignComponentEditPolicy());
	}

	protected void refreshVisuals() {
		refreshAll();
	}

	public void refreshAll() {
		//refreshChildren();
		resizeFigure();

		getFigure().revalidate();
	}

	private void resizeFigure() {
		int width = 0;
		int height = 0;

		List subAreas = ((AreaTemplate) getModel()).getSubAreaContainer().getChildren();
		for (int i=0;i<subAreas.size();i++) {
			SubArea subArea = (SubArea) subAreas.get(i);

			/*int figureHeight = 0;
			try {
				figureHeight = ((SubAreaPart) ((SubAreaContainerPart) getChildren().get(1)).getChildren().get(i)).getFigure().getSize().height;
			} catch (Exception e) {

			}

			width = getAreaWidth();
			height += figureHeight == 0 ? (subArea instanceof HorizontalSubAreaContainer ? GridSubArea.MODEL_HEIGHT : SubArea.MODEL_HEIGHT) : figureHeight;*/

			width = getAreaWidth();
			height += subArea.getHeight() == 0 ? (subArea instanceof HorizontalSubAreaContainer ? GridSubArea.MODEL_HEIGHT : SubArea.MODEL_HEIGHT) : subArea.getHeight();

			if (i < subAreas.size()-1)
				height -= 1;
		}

		getFigure().setSize(width + AreaTemplateTitle.DEFAULT_WIDTH, height);

		if (getParent() instanceof MiplatformDesignPart)
			((MiplatformDesignPart) getParent()).resizeFigure();
	}

}
